/**
 * Created by jinsebainian on 2017/9/22.
 */
// var server = require("./router/server"),
//     router = require("./router/router"),
//     requestHandlers = require("./router/requestHandlers");
//
// // handle 保存不同请求路径对应的处理方法
// var handle = {};
// handle["/"] = requestHandlers.start;
// handle["/start"] = requestHandlers.start;
// handle["/upload"] = requestHandlers.upload;
//
// // 传入路由模块方法, 路径处理方法
// server.start(router.route, handle);
var http = require("http");
var request = require("request");
var express = require('express');
var cookieParser = require('cookie-parser')
// session功能
var session = require('express-session');
var bodyParser = require('body-parser');
// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({ extended: false })

var app = express()
app.use(cookieParser())

// secret是设置在cookie里的sessionkey
app.use(session({'secret':'WBLOG'}))

app.use(express.static('views'));
var User=require('./model/User');
var UserDao = require('./dao/userDao');
var helper = require('./common/db');

//指定模板引擎
app.set("view engine", 'ejs');
//指定模板位置
app.set('views', __dirname + '/views');

app.get('/', function (req, res) {
    var session = req.session;
    let error='';
    try{
        error=session.obj;
    }catch (e){
        error="";
    }
    res.render('login.ejs', {
        title:'登录',
        error:error
    });
})
app.get('/login', function (req, res) {
    var session = req.session;
    let error='';
    try{
        error=session.obj;
    }catch (e){
        error="";
    }
    res.render('login.ejs', {
        title:'登录',
        error:error
    });
})
app.get('/regist', function (req, res) {
    var session = req.session;
    let error='';
    try{
        error=session.obj;
    }catch (e){
        error="";
    }
    res.render('regist.ejs', {
        title:'注册',
        error:error
    });
})

app.post('/login', urlencodedParser, function (req, res) {
    // 输出 JSON 格式
    var response = {
        "userName":req.body.userName,
        "password":req.body.password
    };
    user = new User();
    user.setName(response.userName);
    user.setPassword(response.password);

    new UserDao().login(user,function (result) {
        console.log("--"+result.success)
        if(result.success){
            console.log("--data"+result.data)
            var session = req.session;
            session.name = user.getUserName();
            res.redirect('/index');
        }else{
            console.log("--info"+result.info)
            var session = req.session;
            session.obj = result.info
            res.redirect('/');
        }
    });
})

app.post('/regist', urlencodedParser, function (req, res) {
    // 输出 JSON 格式
    var response = {
        "userName":req.body.userName,
        "password":req.body.password
    };
    user = new User();
    user.setName(response.userName);
    user.setPassword(response.password);

    new UserDao().regist(user,function (result) {
        console.log("--"+result.success)
        if(result.success){
            console.log("--data"+result.data)
            var session = req.session;
            session.name = user.getUserName();
            res.redirect('/login');
        }else{
            console.log("--info"+result.info)
            var session = req.session;
            session.obj = result.info
            res.redirect('/regist');
        }
    });
})

app.get('/index', function (req, res) {
    var session = req.session;
    let name=session.name;
    getData(function (result) {
        res.writeHead(200, {
            "Content-Type": "text/html;charset=utf-8"
        });
        res.end(JSON.stringify(result))
    });
})

var server = app.listen(3000, function () {
    var host = server.address().address
    var port = server.address().port
    console.log("应用实例，访问地址为 http://%s:%s", '127.0.0.1', '3000')
})

function getData(callback) {
    var data={
        from:1,
        pagerCount:2
    };
    request({
        url: "https://www.wjp147.cn/footprint/api_active_list",
        method: "POST",
        json: true,
        headers: {
            "content-type": "application/json",
        },
        body: JSON.stringify(data)
    }, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            callback(response.body)
        }else{
            console.log("---error:"+error+",response.statusCode :"+response.statusCode )
        }
    });
}